package com.hxkj.client.service.taglib.directive;

import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Tags;
import com.hxkj.domain.po.WebsiteAddr;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_HOT_TAGS;

/**
 * @ClassName HotTagsDirective 热词tag标签解析
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/8/21 12:06
 * @Version 1.0
 */
@Component
@Log4j
public class HotTagsDirective extends AbstractDirective {

    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，是否排序,0：升序，1：降序
     */
    public static final String SORT = "sort";
    /**
     * 输入参数，获取参数条数
     */
    public static final String COUNT = "count";
    /**
     * 热门tags的列表
     */
    public static final String HOT_TAGS = "hotTagsList";
    /**
     * 最新tags的列表
     */
    public static final String NEW_TAGS = "newTagsList";

    /**
     * 热门tags分页
     */
    public static final String HOT_TAGS_PAGE = "hotPageInfo";
    /**
     * 最新tags分页
     */
    public static final String NEW_TAGS_PAGE = "newPageInfo";

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws
            TemplateException, IOException {
        env.getOut();
        try {
            //Mr.zheng:获取参数
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            //Mr.zheng:默认根据降序排序
            String sort = super.getString(SORT, params) == null ? "quote_count DESC" : super.getString(SORT, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? 20 : super.getInt(COUNT, params);
            String note = super.getNote(env);
            //Mr.zheng:封装查询参数
            Tags tags = new Tags();

            tags.setSiteId(siteId);
            tags.setCount(count);

            // Redis缓存取值
            List<Tags> hotTagsList = null;
            List<Tags> newTagsList = null;
            PageTo hotPageInfo = null;
            PageTo newPageInfo = null;

            if (null == hotTagsList || hotTagsList.size() == 0 || null == newTagsList || newTagsList.size() == 0 || null == hotPageInfo || null == newPageInfo) {
//            hotTagsList = (List<Tags>) redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_hotTagsList").get();
//            newTagsList = (List<Tags>) redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_newTagsList").get();
//            hotPageInfo = (PageTo) redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_hotPageInfo").get();
//            newPageInfo = (PageTo) redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_newPageInfo").get();
//
//            if (null == hotTagsList || null == newTagsList || null == hotPageInfo || null == newPageInfo) {


                //Mr.zheng:热门tags
                tags.setSort(sort);
                ResultPageStruct<Tags> resultPageStruct = getTagsResultPageStruct(tags);
                hotTagsList = resultPageStruct.getData();
                hotPageInfo = resultPageStruct.getPageInfo();
                hotPageInfo.setCondition(sort);
                //Mr.zheng:最新tags
                tags.setSort("create_time DESC");
                ResultPageStruct<Tags> result = getTagsResultPageStruct(tags);
                newTagsList = result.getData();
                newPageInfo = result.getPageInfo();
                newPageInfo.setCondition(tags.getSort());

                if (StringUtils.isNotBlank(note)) {
                    WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
                    for (Tags tag : hotTagsList) {
                        tag.setManuscriptPath(websiteAddr.getIpAdd() + tag.getManuscriptPath());
                    }
                    for (Tags tag : newTagsList) {
                        tag.setManuscriptPath(websiteAddr.getIpAdd() + tag.getManuscriptPath());
                    }
                } else {
                    Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                    Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                    for (Tags item : hotTagsList) {
                        String urlContext = siteCtxMap.get(item.getSiteId());
                        if (StringUtils.isNotBlank(urlContext)) {
                            item.setManuscriptPath(urlContext + item.getManuscriptPath());
                        }
                    }
                    for (Tags item : newTagsList) {
                        String urlContext = siteCtxMap.get(item.getSiteId());
                        if (StringUtils.isNotBlank(urlContext)) {
                            item.setManuscriptPath(urlContext + item.getManuscriptPath());
                        }
                    }
                }
//                redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_hotTagsList").set(hotTagsList);
//                redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_newTagsList").set(newTagsList);
//                redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_hotPageInfo").set(hotPageInfo);
//                redisTemplate.boundValueOps("directive_" + siteId + CMS_HOT_TAGS + "_newPageInfo").set(newPageInfo);
//            }
                env.setVariable(HOT_TAGS, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(hotTagsList));
                env.setVariable(NEW_TAGS, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(newTagsList));
                env.setVariable(HOT_TAGS_PAGE, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(hotPageInfo));
                env.setVariable(NEW_TAGS_PAGE, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(newPageInfo));

                String userToken = super.getUserToken(env);
                Writer out = env.getOut();
                if (body != null) {
                    if (StringUtils.isEmpty(note)) {
                        body.render(env.getOut());
                    } else {
                        Map<String, String> maps = new LinkedHashMap<>();

                        maps.put(CMS_HOT_TAGS, "");
                        maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                        maps.put(SORT, super.getString(SORT, params));
                        maps.put(COUNT, String.valueOf(getInt(COUNT, params)));
                        try {
                            super.print(body, maps, env, userToken, params);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    throw new RuntimeException("热点标签所在模板至少要加一个空格");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
